# -*- coding: utf-8 -*-
"""
Created on Sat Dec 29 14:04:06 2012

@author: Winand
"""

from webapi import http
from webapi.log import debug, error
from settings import SERVICELIST, BASE_HTML, SRV_ROOT_PATH, SRV_CONF_ROOT_PATH, SRV_AJAX_ROOT_PATH
services = dict(zip(SERVICELIST, map(__import__, \
    ["services."+serv+"."+serv for serv in SERVICELIST], (),(), SERVICELIST)))
debug("Imported services", [serv.__name__ for serv in services.values()])

#def google_proc(path, resp):
#    debug('goofle has been executed on path ', path)
#    http.redirResponse(resp, "http://www.google.com")
    
def main_page(path, resp):
    http.templateResponse(resp, "tpl_home.html", \
                        {#'title': "lancomm homepage",
                        #'page_name': "lancomm",
                        #'page_desc': "Welcome to lancomm. Choose a service",
                        'serv_count': len(services),
                        'serv_name': [serv.name for serv in services.values()],
                        'serv_desc': [serv.description for serv in services.values()],
                        'serv_path': [serv.path for serv in services.values()],
                        'serv_root': SRV_ROOT_PATH,
                        'serv_conf_root': SRV_CONF_ROOT_PATH,
                        })

#service router
def service_root(path, resp):
    SVC_NOT_FOUND = "Service '%s' not found."
    SVC_NO_RESPONCE = "Service could not process request."
    
    urlpieces = path.strip("/").split("/")
    servicename = urlpieces[1]
    if servicename in services:
        service = services[servicename]
        if urlpieces[0] == SRV_ROOT_PATH:
            service.getPage(urlpieces[2:], resp)
        elif urlpieces[0] == SRV_CONF_ROOT_PATH:
            service.getConfPage(urlpieces[2:], resp)
        elif urlpieces[0] == SRV_AJAX_ROOT_PATH:
            service.getAjaxChunk(urlpieces[2:], resp)
        if not resp.get("responded", False):
            error(servicename, SVC_NO_RESPONCE)
            http.htmlResponse(resp, BASE_HTML % SVC_NO_RESPONCE)
    else: http.htmlResponse(resp, BASE_HTML % SVC_NOT_FOUND % servicename)
